<template>
  <div class="app-container">
    <!-- <el-row :gutter="20">
			<el-col :span="5" >
				<div class="tltle" style="height:28px">
					水管机构
				</div>
				<div class="grid-content bg-purple">
					<el-tree :data="deptOptions" node-key="orgCd" :default-expanded-keys="[]" :default-checked-keys="[]" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
				</div>
			</el-col>
			<el-col :span="19">
        <el-row style="height:28px" :gutter="10" class="mb8" type="flex" align="middle" justify="space-between">
          <el-col :span="1.5">
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item>水管机构</el-breadcrumb-item>
              <el-breadcrumb-item v-for="(item,index) in levelList" :key="index">
                <span v-if="index==levelList.length-1" class="no-redirect">{{item}}</span>
                <span v-else>{{ item }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </el-col>
        </el-row> -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="年度" prop="syYear">
        <el-date-picker
          v-model="queryParams.year"
          align="left" type="year"
          placeholder="选择年度"
          value-format="yyyy"
          format="yyyy"
          size="small" >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="水管机构" prop="orgCd" width="50px">
        <treeselect
          v-model="queryParams.orgCd"
          :options="deptOptions"
          :disable-branch-nodes="true"
          :normalizer="normalizer"
          :show-count="true"
          placeholder="水管机构"
          @select="selectAd"
        />
      </el-form-item>
      <el-form-item v-if="feeKind == 0" label="农户" prop="farmCd">
          <el-select v-model="queryParams.farmCd" @change="$forceUpdate()">
                <el-option
                    v-for="item in WiFarmerBList"
                    :key="item.farmCd"
                    :label="item.farmNm"
                    :value="item.farmCd"
                ></el-option>
            </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <!-- <el-button type="primary" size="small" @click="handleAdd">缴费</el-button> -->
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="WrPriceList" >
        <!-- <el-table-column label="次数" type="index" width="80" align="center" /> -->
        <el-table-column label="水费年度" align="center" prop="feeYr" />
        <el-table-column label="机构" v-if="feeKind == 1" align="left" prop="orgNm" />
        <el-table-column label="农户" v-else align="left" prop="farmNm" />
        <el-table-column label="总应收水费" align="center" prop="totalFee">
        </el-table-column>
        <!-- <el-table-column label="当前应收水费" align="center" prop="curFee">
        </el-table-column> -->
        <el-table-column label="实收水费" align="center" prop="payFee">
        </el-table-column>
        <el-table-column label="缴后欠缴" align="center" prop="saveFee">
        </el-table-column>
        <el-table-column label="收费人" prop="lastOper" />
        <el-table-column label="缴费日期" prop="lastTime" />
        <el-table-column label="操作" align="center" width="210px" >
            <template slot-scope="scope">
                <el-row>

                    <el-button  type="primary" plain icon="el-icon-edit"  @click="handleUpdate(scope.row)" >缴费</el-button>

                    <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" >删除</el-button> -->
                </el-row>
            </template>
        </el-table-column>
    </el-table>
    <!-- </el-col>
    </el-row> -->
    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
            <div class="diologbtcss" >已缴情况</div>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="本年应收（元）" >
                        <el-input v-model="form.totalFee" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="实收水费（元）" >
                        <el-input v-model="form.payFee" disabled />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="已缴次数" >
                        <el-input v-model="form.countSum" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="剩余金额（元）" >
                        <el-input v-model="form.saveFee" disabled />
                    </el-form-item>
                </el-col>
            </el-row>
            <div class="diologbtcss" >本次缴纳</div>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="本次缴纳（元）" >
                        <el-input v-model="form.curFee" type="Number" :disabled="dialogtype=='info'" />
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="11">
                    <el-form-item label="缴费方式" >
                        <el-input v-model="form.payType" :disabled="dialogtype=='info'" />
                    </el-form-item>
                </el-col> -->
            </el-row>
            <!-- <el-row>
                <el-col :span="22">
                    <el-form-item label="经办人" >
                        <el-input v-model="form.operator" :disabled="dialogtype=='info'" />
                    </el-form-item>
                </el-col>
            </el-row> -->
            <el-row v-show="dialogtype!='info'" >
                <el-col :span="22">
                    <el-form-item label="收缴凭证" prop="file">
                        <el-upload

                            :action="uploadImgUrl"
                            list-type="picture-card"
                            :on-success="handleUploadSuccess"
                            :before-upload="handleBeforeUpload"
                            :limit="limit"
                            :on-error="handleUploadError"
                            :on-exceed="handleExceed"
                            name="pzfile"
                            :on-remove="handleRemove"
                            :show-file-list="true"
                            :headers="headers"
                            :file-list="fileList"
                            :on-preview="handlePictureCardPreview"
                            :class="{hide: this.fileList.length >= this.limit}"
                        >
                        <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row v-show="dialogtype=='info'" >
                <el-col :span="22">
                    <el-form-item label="收缴凭证" prop="file">
                        <img v-for="(item,index) in fileList" :key="index"
                        :src="item.url" style=" max-width: 146px; height: 146px;  margin: 0 15px" />
                    </el-form-item>
                </el-col>
            </el-row>

      </el-form>
      <div slot="footer" v-show="dialogtype!='info'" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确认缴纳</el-button>
        <el-button @click="cancel">取消缴纳</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>

  </div>
</template>

<script>
import { getOrgacctpayOrgFee ,getFarmacctpayOrgFee,payFarmFee,payOrgFee} from "@/api/waterPrice/WitakeOver";
import { organtreeList,getFeeKind } from "@/api/common";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listWiFarmerB} from "@/api/datam/WiFarmerB";
import { getToken } from "@/utils/auth";
export default {
  name: "WrPrice",
  components: { Treeselect },
  data() {
    return {
      // 行政区划树选项
      WiFarmerBList:[],
      deptOptions:[],
      levelList:[],
      defaultProps: {
        children: 'children',
        label: 'orgNm'
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 水价设定表格数据
      WrPriceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        year: null,
        orgCd: 'ORG6543220000'
      },
      feeKind:'1',
      // 表单参数
      form: {
        totalFee: null,
        cumPay: null,
        countSum: null,
        saveFee: null,
        curFee: null,
        payType: null,
        operator: null,
        proofPath: [],
        orgCd: null,
        year: null,
        code: null
      },

      // 表单校验
      rules: {
      },
      dialogtype: null,
      btname: "",


      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/waterPrice/WiFarmacctY/uploadPZFile", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      selectlisttype:2,
      limit: 5,
      // 大小限制(MB)
      fileSize: 5,
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: ["png", "jpg", "jpeg"],
      // 是否显示提示
      isShowTip:true,
    };
  },
  created() {
    var dt = new Date();
    var year = dt.getFullYear()
    this.queryParams.year = year+"";
    this.btname = "阿克苏市"
    this.getTreeselect();
    this.getFeeKindtype();
  },
  methods: {
    // 删除图片
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if(findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      this.fileList.push({ name: res.data, url: res.data });
      this.$emit("input", this.listToString(this.fileList));
      this.loading.close();
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$message.error(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$message({
        type: "error",
        message: "上传失败",
      });
      this.loading.close();
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    selectItem(e){
        if(e.adGrad==6){
            this.selectlisttype = 1;
        }else if(e.adGrad==4||e.adGrad==5){
            this.selectlisttype = 2;
        }
        this.btname = e.adName;
    },
    handleAdd(){
        this.reset();
        this.dialogtype = "add";
        this.getaddinfo();
    },
    handleUpdate(row){
        this.reset();
        this.dialogtype = "update";
        this.form = row
        if(row.voucherPath){
          let fl = row.voucherPath;
          fl.forEach(f => {
              this.fileList.push({ name: f, url: f });
          });
        }
        this.open = true;
    },
    getaddinfo(){
        let param = {
          feeYr:this.queryParams.year,
          orgCd:this.queryParams.orgCd,
          payFee:this.form.curFee,
          isOk:'1',
        }
        let flist = this.fileList;
        param.voucherPath = [];
        flist.forEach(f => {
            param.voucherPath.push(f.url);
        });
        if(this.feeKind == 1){
          payOrgFee(param).then(res => {
              this.$message({
                type: "success",
                message: "缴费成功",
              });
              this.open = false
              this.getList()
          })
        }else{
          param.farmCd = this.queryParams.farmCd,
          payFarmFee(param).then(res => {
            this.$message({
                type: "success",
                message: "缴费成功",
              });
              this.open = false
              this.getList()
          })
        }

    },

    handleDelete(rd){
        this.$modal.confirm('是否确认删除缴费记录信息？').then(function() {
            return deleteWrPay({code:rd.code});
        }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    // 获取区划名称
    selectAd(val) {
      this.getlistWiFarmer()
    },
    // 获取收缴方式  0按农户 1按机构 year=2023
    getFeeKindtype(){
      getFeeKind({year: this.queryParams.year}).then(res => {
        this.feeKind = res.data.feeKind
      })
    },

    /** 查询水价设定列表 */
    getList() {

      if(this.feeKind == 1){
        this.loading = true;
        getOrgacctpayOrgFee( this.queryParams.year,this.queryParams.orgCd).then(response => {
            this.WrPriceList = response.data?[response.data]:[];
            // this.total = response.total;
            this.loading = false;
        });
      }else{
        if(this.queryParams.farmCd == '' || this.queryParams.farmCd == null){
          this.$message({
            message: '请选择农户',
            type: 'warning'
          });
          return false;
        }
        this.loading = true;
        getFarmacctpayOrgFee( this.queryParams.year,this.queryParams.farmCd).then(response => {
            this.WrPriceList = response.data?[response.data]:[];
            // this.total = response.total;
            this.loading = false;
        });
      }
    },
    getOrgIdArr(data, val) { //递归父级key
      for (const element of data) {
        if (element.orgNm == val) {
          return [element.orgNm];
        }
        if (element.children) {
          var far = this.getOrgIdArr(element.children, val);
          if (far) {
            return far.concat(element.orgNm);
          }
        }
      }
    },
     handleNodeClick(data) {
      if (data) {
        const result = this.getOrgIdArr(this.deptOptions, data.orgNm).reverse()
        this.levelList = result
        this.queryParams.orgCd = data.orgCd
        this.getlistWiFarmer();
      }
    },
    /** 查询行政区域下拉树结构 */
    getTreeselect() {
      organtreeList({}).then((response) => {
        this.deptOptions = this.handleTree(response.data, "orgCd", "parentOrgCd");
        this.getlistWiFarmer()
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.orgCd,
        label: node.orgNm,
        children: node.children,
      };
    },
    /** 查询农户信息登记列表 */
    getlistWiFarmer() {
      listWiFarmerB({orgCd:this.queryParams.orgCd }).then(response => {
        this.WiFarmerBList = response.rows;
        if(this.feeKind == 0 ){
          this.queryParams.farmCd =  response.rows[0].farmCd
        }
         setTimeout(() => this.getList(),300)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
        this.form = {
            totalFee: null,
            cumPay: null,
            countSum: null,
            saveFee: null,
            curFee: null,
            payType: null,
            operator: null,
            proofPath: [],
            orgCd: null,
            year: null,
            code: null
        }
        this.fileList = [];
        this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
        this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 提交按钮 */
    submitForm() {
      if(!this.form.curFee){
        this.$message({
          type: "error",
          message: "请输入缴纳费用",
        });
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
            this.getaddinfo()
        }
      });
    },

  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .btncss{
        width: 100%;
        margin-top:20px;
        text-align: right;
    }

    .btcss{
        width: 100%;
        text-align: center;
        font-size: 18px;
        font-weight: 600;
        margin: 20px 0;
    }

    .diologbtcss{
        width: 100%;
        text-align: center;
        font-size: 18px;
        font-weight: 550;
        margin: 20px 0;
    }

</style>
